package com.suman.bbcticker.configure;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.DialogPreference;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.AdapterView.OnItemClickListener;

public class AutoCompleteTextViewPreference extends DialogPreference implements OnItemClickListener{
	public static final int autoCompleteTextViewPreferenceStyle = 16842898;
	

	 /**
     * The edit text shown in the dialog.
     */
    private AutoCompleteTextView mEditText;
    
    private String mText;


	private Context myContext;
    
    public AutoCompleteTextViewPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        myContext = context;
        
        mEditText = new AutoCompleteTextView(context, attrs);
        
        // Give it an ID so it can be saved/restored
        mEditText.setId(16908291);
        
        /*
         * The preference framework and view framework both have an 'enabled'
         * attribute. Most likely, the 'enabled' specified in this XML is for
         * the preference framework, but it was also given to the view framework.
         * We reset the enabled state.
         */
        mEditText.setEnabled(true);
    }

    public AutoCompleteTextViewPreference(Context context, AttributeSet attrs) {
        this(context, attrs, autoCompleteTextViewPreferenceStyle);
    }

    public AutoCompleteTextViewPreference(Context context) {
        this(context, null);
    }
    
    /**
     * Saves the text to the {@link SharedPreferences}.
     * 
     * @param text The text to save
     */
    public void setText(String text) {
        final boolean wasBlocking = shouldDisableDependents();
        
        mText = text;
        
        persistString(text);
        
        final boolean isBlocking = shouldDisableDependents(); 
        if (isBlocking != wasBlocking) {
            notifyDependencyChange(isBlocking);
        }
    }
    
    /**
     * Gets the text from the {@link SharedPreferences}.
     * 
     * @return The current preference value.
     */
    public String getText() {
        return mText;
    }

    @Override
    protected void onBindDialogView(View view) {
    	
        super.onBindDialogView(view);
        

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(myContext, com.suman.bbcticker.R.array.ticker_siteselectionpreferences_entries_list, android.R.layout.simple_dropdown_item_1line);

        AutoCompleteTextView editText = mEditText;
        
        editText.setText(getText());
        editText.setAdapter(adapter);
        
        ViewParent oldParent = editText.getParent();
        if (oldParent != view) {
            if (oldParent != null) {
                ((ViewGroup) oldParent).removeView(editText);
            }
            onAddEditTextToDialogView(view, editText);
        }
    }

    /**
     * Adds the EditText widget of this preference to the dialog's view.
     * 
     * @param dialogView The dialog view.
     */
    protected void onAddEditTextToDialogView(View dialogView, AutoCompleteTextView editText) {
        ViewGroup container = (ViewGroup) dialogView
                .findViewById(16908733);
        if (container != null) {
            container.addView(editText, ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }
    
    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
        
        if (positiveResult) {
            String value = mEditText.getText().toString();
            if (callChangeListener(value)) {
                setText(value);
            }
        }
    }

    @Override
    protected Object onGetDefaultValue(TypedArray a, int index) {
        return a.getString(index);
    }

    @Override
    protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
        setText(restoreValue ? getPersistedString(mText) : (String) defaultValue);
    }

    @Override
    public boolean shouldDisableDependents() {
        return TextUtils.isEmpty(mText) || super.shouldDisableDependents();
    }

    /**
     * Returns the {@link EditText} widget that will be shown in the dialog.
     * 
     * @return The {@link EditText} widget that will be shown in the dialog.
     */
    public AutoCompleteTextView getEditText() {
        return mEditText;
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        final Parcelable superState = super.onSaveInstanceState();
        if (isPersistent()) {
            // No need to save instance state since it's persistent
            return superState;
        }
        
        final SavedState myState = new SavedState(superState);
        myState.text = getText();
        return myState;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state == null || !state.getClass().equals(SavedState.class)) {
            // Didn't save state for us in onSaveInstanceState
            super.onRestoreInstanceState(state);
            return;
        }
         
        SavedState myState = (SavedState) state;
        super.onRestoreInstanceState(myState.getSuperState());
        setText(myState.text);
    }
    
    private static class SavedState extends BaseSavedState {
        String text;
        
        public SavedState(Parcel source) {
            super(source);
            text = source.readString();
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeString(text);
        }

        public SavedState(Parcelable superState) {
            super(superState);
        }

        public static final Parcelable.Creator<SavedState> CREATOR =
                new Parcelable.Creator<SavedState>() {
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
    
    
    static final String[] COUNTRIES = new String[] {
    	"Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
    	"Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
    	"Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
    	"Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
    	"Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
    	"Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
    	"British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
    	"Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
    	"Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
    	"Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
    	"Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
    	"Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
    	"East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
    	"Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
    	"Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
    	"French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
    	"Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
    	"Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
    	"Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
    	"Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
    	"Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
    	"Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
    	"Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
    	"Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
    	"Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
    	"Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
    	"Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
    	"Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
    	"Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
    	"Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
    	"Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
    	"Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
    	"Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
    	"Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
    	"Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
    	"The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
    	"Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
    	"Ukraine", "United Arab Emirates", "United Kingdom",
    	"United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
    	"Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
    	"Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
        };

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
		String itemAtPosition = (String) parent.getItemAtPosition(position);
		mText = itemAtPosition;
		
		
	}

}
